# app.py
from flask import Flask, jsonify
from flask_cors import CORS
from config import Config
from models import db
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from api.events import events_bp
from api.appeals import appeals_bp
from api.reports import reports_bp
from api.reported import reported_bp
from api.user import user_blueprint

from flask import request
import random
import time
import os  # 添加导入


# 用于存储验证码（模拟数据库）
verification_codes = {}
# 可能无法并发

app = Flask(__name__)
CORS(app)

# 加载配置
app.config.from_object(Config)
# 初始化数据库
db.init_app(app)
# 注册蓝图
app.register_blueprint(events_bp, url_prefix='/api')
app.register_blueprint(appeals_bp, url_prefix='/api')
app.register_blueprint(reports_bp, url_prefix='/api')
app.register_blueprint(reported_bp, url_prefix='/api')
app.register_blueprint(user_blueprint, url_prefix='/api')

# 创建所有表
with app.app_context():
    db.create_all()

migrate = Migrate(app, db)

# 主页路由
@app.route("/")
def index():
    return "Hello, World!"
    



# 车辆位置接口
@app.route('/api/get_location', methods=['GET'])
def get_location():
    return jsonify({
        "latitude": 39.909187,  # 北京天安门
        "longitude": 116.397451
    })


# 发送验证码接口
@app.route('/api/sendVerificationCode', methods=['POST'])
def send_verification_code():
    phone_number = request.json.get('phone_number')
    if not phone_number:
        return jsonify({'message': '手机号不能为空'}), 400

    # 生成验证码并存储
    code = random.randint(100000, 999999)
    verification_codes[phone_number] = {'code': code, 'expire_at': time.time() + 300}
    print(f"发送验证码: {code} 到 {phone_number}")  # 调试信息
    return jsonify({'message': '验证码发送成功'})


# 验证验证码接口
@app.route('/api/verifVerificationCode', methods=['POST'])
def verify_verification_code():
    phone_number = request.json.get('phone_number')
    code = request.json.get('code')

    if phone_number in verification_codes:
        data = verification_codes[phone_number]
        if time.time() < data['expire_at'] and data['code'] == int(code):
            return jsonify({'message': '验证码验证成功'})
        return jsonify({'message': '验证码无效或已过期'}), 400
    return jsonify({'message': '验证码不存在'}), 400




# 宝塔中不会执行
if __name__ == '__main__':
    app.run(debug=True)












